package com.spring.Mail;

import com.spring.Entity.ContractEntity;
import com.spring.Entity.UserEntity;
import com.spring.Exception.MailAddressException;
import com.spring.Service.Interface.ContractService;
import com.spring.Service.Interface.UserServie;
import com.spring.Util.JavaMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by Arabira on 2016/8/8.
 */
@Component
public class ContractMail {
    @Autowired
    private ContractService contractService;
    @Autowired
    private UserServie userServie;
    private JavaMail javaMail;
    private String host;
    private String senderAddr;
    private String userName;
    private String password;

    public ContractMail() {
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setSenderAddr(String senderAddr) {
        this.senderAddr = senderAddr;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void run() {
        ContractEntity[] contracts = contractService.findContractByRemindTime();
        if (contracts.length > 0) {
            javaMail = new JavaMail();
            javaMail.initSender(host, senderAddr, userName, password);
            for (ContractEntity contract : contracts) {
                UserEntity userEntity = userServie.findById(contract.getUserId());
                String content = "尊敬的" + userEntity.getName() + "先生/女士您好：\r\n" +
                        "    您的合同 " + contract.getContractName() + " （合同号：" + contract.getId() + "） 即将于" + contract.getDeadline()
                        + "到期，请您注意，谢谢。";
                javaMail.initReceiver(userEntity.getEmailAddress(), "合同到期提醒", content, false, "2000");
                try {
                    javaMail.send();
                } catch (MailAddressException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
